package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;

import com.swgk.core.util.LogUtil;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddStorage3Binding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.transport.MapLongAndLatEntity;
import com.sgb.kjwl.model.entity.user.AddDeviceEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.view.event.self.GoodsEvent;
import com.sgb.alimaplibrary.SelectAddressActivity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.viewmodel.self.publish.AddStorageModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.MToast;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import javax.inject.Inject;

import static com.swgk.core.event.EventConstant.EVENT_STORAGE_ADD;

public class AddStorageActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private static final String TAG = "AddStorageActivity";
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private ActivityAddStorage3Binding binding;

    public static final int REQUESTCODE_CHOOSE_ADDRESS = 100;
    private AddDeviceEntity addDeviceEntity = new AddDeviceEntity();
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;

    private boolean isLoaded = false;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private GoodsEvent goodsEvent;
    private MapLongAndLatEntity currentSelectedLatlng = new MapLongAndLatEntity();
    private String currentCity = "";
    @Inject
    AddStorageModel viewModel;

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, AddStorageActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }


    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(AddStorageActivity.this, R.layout.activity_add_storage3);
        binding.setViewModel(viewModel);
        binding.backView.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvArea.setOnWholeItemClickListener(this);
        binding.itemDetailArea.setOnWholeItemClickListener(this);

        binding.nS.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        binding.nS.setFocusable(true);
        binding.nS.setFocusableInTouchMode(true);
        binding.nS.setOnTouchListener((v, event) -> {
            v.requestFocusFromTouch();
            return false;
        });
    }

    @SuppressWarnings("unchecked")
    @Override
    protected void init() {
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
    }


    //注册地址
    public void showAddressPop(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    @SuppressWarnings("unchecked")
    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(AddStorageActivity.this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
//                Objects.requireNonNull(viewModel.storageInfoEntity.get()).setDistrictName(areaName);
                Objects.requireNonNull(viewModel.storageManEntity.get()).setDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
            }
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.itemTvArea.setContent(content);
            cityPosition1 = options1;
            cityPosition2 = options2;
//            Objects.requireNonNull(viewModel.storageInfoEntity.get()).setProvinceName(addressEntityList.get(options1).getName());
            Objects.requireNonNull(viewModel.storageManEntity.get()).setProvinceNo(addressEntityList.get(options1).getId());
//            Objects.requireNonNull(viewModel.storageInfoEntity.get()).setCityName(opt2.get(options1).get(options2).getName());
            Objects.requireNonNull(viewModel.storageManEntity.get()).setCityNo(opt2.get(options1).get(options2).getNo());
            currentCity = opt2.get(options1).get(options2).getName();
            viewModel.getSelectedAddressLatlng(addressEntityList.get(options1).getNo(), opt2.get(options1).get(options2).getNo(), opt3.get(options1).get(options2).get(options3).getNo());
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.setTitleText("选择仓储地区");
        cityOption.show();
    }

    public void fillCurrentAddressLatlng(MapLongAndLatEntity data) {
        this.currentSelectedLatlng = data;
    }

    public void showSuccess() {
        goodsEvent = new GoodsEvent();
        goodsEvent.setMessageTag(EVENT_STORAGE_ADD);
        EventBus.getDefault().post(goodsEvent);
        finish();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.next_view:
                if (TextUtils.isEmpty(binding.itemTvName.getContent())) {
                    MToast.showToast(AddStorageActivity.this, "请输入仓储名称");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvArea.getContent())) {
                    MToast.showToast(AddStorageActivity.this, "请选仓储地址");
                    return;
                } else if (TextUtils.isEmpty(binding.itemDetailArea.getContent())) {
                    MToast.showToast(AddStorageActivity.this, "请输入详细地址");
                    return;
                }
                viewModel.storageManEntity.get().setDetailsAddress(binding.itemDetailArea.getContent());
                viewModel.saveStorage();
                break;
            case R.id.back_view:
                finish();
                break;
        }
    }


    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_area:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
            case R.id.item_detailArea:
                Intent intent = new Intent();
                intent.setClass(this, SelectAddressActivity.class);
                intent.putExtra(SelectAddressActivity.TITLE, "选择仓储地址");
                intent.putExtra(SelectAddressActivity.CITY, currentCity);
                if (!TextUtils.isEmpty(currentSelectedLatlng.getLat())) {
                    intent.putExtra(SelectAddressActivity.LATITUDE, Double.parseDouble(currentSelectedLatlng.getLat()));
                }
                if (!TextUtils.isEmpty(currentSelectedLatlng.getLng())) {
                    intent.putExtra(SelectAddressActivity.LONGTITUDE, Double.parseDouble(currentSelectedLatlng.getLng()));
                }
                startActivityForResult(intent, REQUESTCODE_CHOOSE_ADDRESS);
                break;
        }
    }


    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        //城市列表
        @SuppressWarnings("MismatchedQueryAndUpdateOfCollection") List<AddressEntity<List<AddressEntity>>> cityList;
        //区域列表
        List<List<AddressEntity>> areaList;
        for (int x = 0; x < addressEntityList.size(); x++) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            if (addDeviceEntity != null && addDeviceEntity.getLocation().getProvinceName() != null && addDeviceEntity.getLocation().getProvinceName().equals(addressEntityList.get(x).getName())) {
                cityPosition1 = x;
            }
            opt2.add(addressEntityList.get(x).getChildren());
            for (int i = 0; i < addressEntityList.get(x).getChildren().size(); i++) {
                cityList.add(addressEntityList.get(x).getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (addressEntityList.get(x).getChildren().get(i).getChildren() == null
                        || addressEntityList.get(x).getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(addressEntityList.get(x).getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        if (addDeviceEntity != null) {
            if (addDeviceEntity.getLocation().getCityName() != null)
                for (int x2 = 0; x2 < opt2.size(); x2++) {
                    if (addDeviceEntity.getLocation().getCityName().equals(addressEntityList.get(cityPosition1).getChildren().get(x2).getName())) {
                        cityPosition2 = x2;
                        break;
                    }
                }
            if (addDeviceEntity.getLocation().getAreaName() != null)
                for (int x3 = 0; x3 < opt3.size(); x3++) {
                    if (addDeviceEntity.getLocation().getAreaName().equals(addressEntityList.get(cityPosition1).getChildren().get(cityPosition2).getChildren().get(x3).getName())) {
                        cityPosition3 = x3;
                        break;
                    }
                }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUESTCODE_CHOOSE_ADDRESS) {
                if (data == null) {
                    LogUtil.d(TAG, "choose detail address data is null");
                    return;
                }
                if (data.hasExtra(SelectAddressActivity.CURRENT_POSITION)) {
                    binding.itemDetailArea.setContent(data.getStringExtra(SelectAddressActivity.CURRENT_POSITION));
                }
            }
        }
    }
}

